import {observable, extendObservable, action, toJS} from 'mobx';
import {
  getBlock,
  getUnitInfo,
  removePlan,
  deleteUnitInfo,
  batchDeleteBlockInfo,
  pushDoorPwd,
} from 'util/api';
import _ from 'lodash';
import {validateFields} from '../Common.js';
import {message} from 'antd';
import store from 'store';

//导出
export default class HouseholdStore {
  constructor() {
    this.reset(true);
  }

  @action
  reset = init => {
    const state = {
      listData: [],
      listParams: {pageNo: 1, pageSize: 10},
      listLoading: false, // 是否显示加载状态
      indeterminate: false,
      checkAll: false,
      listSelected: 0,
      listChenckedIds: [],
      listPagination: {...this.listParams, total: 0},
      unitData: [],
      unitLoading: false,
      newRoomVisible: false,
      currentBlockId: null,
    };

    if (init) {
      extendObservable(this, state);
    } else {
      Object.keys(state).forEach(key => (this[key] = state[key]));
    }

    this.location = {};
    this.match = {};
    this.history = {};
  };

  //取消新增单元
  @action
  resetFields = async () => {
    this.fields = {
      block: {
        value: '',
        require: true,
      },
      unit: {value: '', require: true},
      password: {value: '', require: true},
    };
  };
  @action
  resetRefresh = async () => {
    this.reset();
    this.getBlock();
  };

  //取消新增单元
  @action
  cancelAddUnit = async () => {
    this.addUnitVisible = false;
    this.resetFields();
  };
  @action
  addUnitOk = async () => {
    //校验字段
    validateFields(
      toJS(this.fields),
      () => {
        this.addUnitVisible = false;
      },
      newFields => {
        this.fields = newFields;
      },
    );
    this.resetFields();
  };
  //改变字段
  @action
  handleFormChange = async changedFields => {
    const key = _.keys(changedFields);
    //showError让自己校验字段;
    const obj = {};
    obj[key] = {showError: false, ...changedFields[key]};
    this.fields = {...toJS(this.fields), ...obj};
  };
  //显示新增单元删除
  @action
  addtionUnit = async () => {
    //清空fields
    this.resetFields();
    this.addUnitVisible = true;
    this.newRoomVisible = false;
  };

  @action
  onWillMount = async (location, match, history) => {
    this.reset();

    this.loading = true;
    await this.getBlock({pageNo: 1, pageSize: 10});
    this.loading = false;
  };

  @action
  onDelete = async record => {
    this.loading = true;
    let res = await deleteUnitInfo({
      unitId: record.unitId,
      block: record.block,
      unit: record.unit,
    });
    this.loading = false;
    if (res.result === 'success') {
      this.getUnitInfo({blockId: record.blockId});
    }
  };

  @action
  onPush = async record => {
    let res = await pushDoorPwd({unitId: record.unitId, unit: record.unit});
    if (res.result === 'success') {
      message.success(res.msg);
      this.getUnitInfo({blockId: record.blockId});
    } else {
      message.error(res.msg);
    }
  };
  @action
  getUnitInfo = async (params = {}) => {
    this.currentBlockId = params.blockId;
    this.unitLoading = true;
    const res = await getUnitInfo(params);
    this.unitLoading = false;

    if (res.result === 'success') {
      this.unitData = res.data;
      return true;
    }
  };

  @action
  getBlock = async (params = {}) => {
    this.listLoading = true;
    const res = await getBlock({...this.listParams, ...params});
    this.listLoading = false;
    if (res.result === 'success') {
      if (res.data[0]) {
        res.data[0]['active'] = true;
        this.listSelected = 0;
      }
      this.listData = res.data;
      this.listPagination = {
        pageNo: res.pageNo,
        pageSize: res.pageSize,
        total: res.total,
      };

      //请求单元列表
      if (res.data[0]) {
        this.getUnitInfo({blockId: res.data[0].blockId});
      }
    }
  };
  //-----
  @action
  onCheckAllChange = async e => {
    if (e.target.checked) {
      this.checkAll = true;
      this.indeterminate = false;
      let ids = [];

      this.listData = toJS(this.listData).map(item => {
        item['checked'] = true;
        ids.push(item.id);
        return item;
      });
      this.listChenckedIds = ids;
    } else {
      this.checkAll = false;
      this.listData = toJS(this.listData).map(item => {
        item['checked'] = false;
        return item;
      });
      this.listChenckedIds = [];
    }
  };
  //列表多选框选中
  @action
  onCheckChange = async (record, index, e) => {
    let listData = toJS(this.listData);
    //选中
    if (e.target.checked) {
      this.listChenckedIds.push(record.blockId);
      listData[index]['checked'] = true;
      this.listData = listData;
    } else {
      this.listChenckedIds = toJS(this.listChenckedIds).filter(item => {
        return item !== record.blockId;
      });
      listData[index]['checked'] = false;
      this.listData = listData;
    }
    //多选框的状态
    let checkedLength = toJS(this.listChenckedIds).length;
    let length = toJS(this.listData).length;
    if (length === checkedLength || checkedLength === 0) {
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }
    if (length === checkedLength) {
      this.checkAll = true;
    } else {
      this.checkAll = false;
    }
  };
  //列表选中
  @action
  listItemClick = async (blockId, index) => {
    let selected = toJS(this.listSelected);
    if (selected === index) return;

    let listData = toJS(this.listData);
    delete listData[selected]['active'];
    listData[index]['active'] = true;
    this.listData = listData;

    this.listSelected = index;
    this.getUnitInfo({blockId});
  };
  //列表选中
  @action
  batchBuildDelete = async params => {
    if (this.listChenckedIds.length === 0) {
      message.error('请选择指定幢数才能删除！');
    } else {
      let res = await batchDeleteBlockInfo({blockList: this.listChenckedIds});
      if (res.result === 'success') {
        this.getBlock();
        this.listChenckedIds = [];
        message.success('批量删除成功!');
      } else {
        message.error('批量删除失败!');
      }
    }
  };
}
